<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class TmpUserService extends BaseService
{
    //用户项目

    //列表
    public function getIndex()
    {
        $res = $this->dbConn($this->dbXm)
            ->where('del', 0)
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return $this->toback(0, '没有项目', []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'serial' => $v['serial'],
            ];
        }
        return $this->toback(0, '', $arys);
    }

    //详情
    public function getOne($itemId)
    {
        $res = (array) $this->dbConn($this->dbXm)->where('id', $itemId)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有项目');
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'serial' => $res['serial'],
        ];
        //文件树
        $frontApi = $this->getDocList($itemId, 1);
        $adminApi = $this->getDocList($itemId, 2);
        $arys['treeList'] = [
            'front_view' => $this->getTree($itemId, 2),
            'front_api' => $frontApi['code']==0 ? $frontApi['data'] : [],
            'admin_view' => $this->getTree($itemId, 1),
            'admin_api' => $adminApi['code']==0 ? $adminApi['data'] : [],
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 项目文件树
     * @param int $item_id 项目ID
     * @param int $client_type 1管理后台页面，2管理后台接口，3用户端页面，4用户端接口
     */
    public function getTree($item_id, $client_type, $pid = 0)
    {
        $treeArys = [];
        $res = $this->dbConn($this->dbXmPath)
            ->where('user_item_id', $item_id)
            ->where('client_type', $client_type)
            ->where('pid', $pid)
            ->get();
        if (!count($res)) {
            return $treeArys;
        }
        foreach ($res as $v) {
            $v = (array) $v;
            $treeArys[] = [
                'fid' => $v['id'],
                'fname' => $v['title'],
                'fpath' => is_file($v['url']) ? $v['url'] : '',
                'childList' => $this->getTree($item_id, $client_type, $v['id']),
            ];
        }
        return $treeArys;
    }

    //获取文件地址
    public function getFileOne($fid)
    {
        return (array) $this->dbConn($this->dbXmPath)->where('id', $fid)->first();
    }

    //接口列表
    public function getDocList($item_id, $clientType)
    {
        $res = $this->dbConn($this->dbXmDoc)
            ->select('id', 'user_item_id', 'client_type', 'title', 'url', 'req_json')
            ->where('del', 0)
            ->where('user_item_id', $item_id)
            ->where('client_type', $clientType)
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有文档数据');
        }
        foreach ($res as $k => $v) {
            $reqJsons = $v->req_json ? json_decode($v->req_json, true) : [];
            $res[$k]->url = env('DOMAIN').$v->url;
            $res[$k]->req_json = $reqJsons;
        }
        return $this->toback(0, '', $res);
    }

    /**
     * 拷一份项目
     * @param int $uid 用户ID
     * @param int $item_id 项目模板ID
     */
    public function copyByUid($uid, $item_id)
    {
        $res = (array) $this->dbConn($this->dbXm)
            ->where('uid', $uid)
            ->where('tmp_id', $item_id)
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '项目已领取');
        }
        $userItemId = 0; //用户项目ID
        $arys = ['serialOld' => '', 'serialNew' => ''];
        //复制项目
        $xmItemOne = (array) $this->dbConn($this->dbXm)
            ->where('del', 0)
            ->where('uid', $uid)
            ->where('tmp_id', $item_id)
            ->first();
        $itemOne = (array) $this->dbConn($this->dbTmp)
            ->where('del', 0)
            ->where('id', $item_id)
            ->first();
        if (empty($itemOne)) {
            return $this->toback(-2, '模板错误');
        }
        $arys['serialOld'] = $itemOne['serial'];
        if (empty($xmItemOne)) {
            $arys['serialNew'] = toUserItemSerial();
            $userItemId = $this->dbConn($this->dbXm)->insertGetId([
                'uid' => $uid, 'tmp_id' => $item_id, 'title' => $itemOne['title'],
                'serial' => $arys['serialNew'], 'addtime' => toDate(), 'uptime' => toDate(),
            ]);
        } else {
            $arys['serialNew'] = $xmItemOne['serial'];
        }
        //复制目录
        $xmPathTotal = $this->dbConn($this->dbXmPath)
            ->where('del', 0)
            ->where('id', $item_id)
            ->count();
        $pathOnes = $this->dbConn($this->dbTmpPath)
            ->where('del', 0)
            ->where('item_id', $item_id)
            ->get();
        if ($userItemId && !$xmPathTotal && count($pathOnes)) {
            foreach ($pathOnes as $v) {
                $v = (array) $v;
                $urls = explode('/', $v['url']);
                $urls[1] = $arys['serialNew'];
                $url = implode('/', $urls);
                $this->dbConn($this->dbXmPath)->insertGetId([
                    'uid' => $uid, 'tmp_id' => $item_id, 'tmp_path_id' => $v['id'],
                    'user_item_id' => $userItemId, 'client_type' => $v['client_type'],
                    'title' => $v['title'], 'url' => $url, 'pid' => $v['pid'],
                    'addtime' => toDate(), 'uptime' => toDate(),
                ]);
            }
        }
        //复制菜单
        $xmMenuTotal = $this->dbConn($this->dbXmMenu)->count();
        if ($userItemId && !$xmMenuTotal) {
            $this->copyMenu($uid, $item_id, $userItemId);
        }
        //复制用户
        $xmUserOnes = $this->dbConn($this->dbXmUser)->get();
        if ($userItemId && !count($xmUserOnes)) {
            $userOnes = $this->dbConn($this->dbTmpUser)->get();
            if (count($userOnes)) {
                foreach ($userOnes as $v) {
                    $v = (array) $v;
                    $this->dbConn($this->dbXmUser)->insertGetId([
                        'uid' => $uid, 'tmp_id' => $item_id, 'tmp_user_id' => $v['id'],
                        'user_item_id' => $userItemId, 'type' => 2, 'nick' => $v['nick'],
                        'passwd' => md5('123456'), 'phone' => $v['phone'],
                        'addtime' => toDate(), 'uptime' => toDate(),
                    ]);
                }
            }
        }
        //复制文档
        $xmDocOnes = $this->dbConn($this->dbXmDoc)->get();
        if ($userItemId && !count($xmDocOnes)) {
            $userDocOnes = $this->dbConn($this->dbTmpDoc)->where('del', 0)->get();
            if (count($userDocOnes)) {
                foreach ($userDocOnes as $v) {
                    $v = (array) $v;
                    $this->dbConn($this->dbXmDoc)->insertGetId([
                        'uid' => $uid, 'tmp_id' => $item_id, 'tmp_doc_id' => $v['id'],
                        'user_item_id' => $userItemId, 'client_type' => $v['client_type'],
                        'title' => $v['title'], 'url' => $v['url'], 'req_json' => $v['req_json'],
                        'del' => $v['del'], 'addtime' => toDate(), 'uptime' => toDate(),
                    ]);
                }
            }
        }
        return $this->toback(0, '', $arys);
    }

    /**
     * 递归复制菜单
     * @param int $uid 用户ID
     * @param int $itemId 模板项目ID
     * @param int $userItemId 用户项目ID
     * @param int $pid 菜单父ID
     */
    public function copyMenu($uid, $itemId, $userItemId, $pid = 0)
    {
        $menuOnes = $this->dbConn($this->dbTmpMenu)
            ->where('item_id', $itemId)
            ->where('pid', $pid)
            ->get();
        if (!count($menuOnes)) {
            return false;
        }
        foreach ($menuOnes as $v) {
            $v = (array) $v;
            $this->dbConn($this->dbXmMenu)->insertGetId([
                'uid' => $uid, 'tmp_id' => $itemId, 'tmp_menu_id' => $v['id'],
                'user_item_id' => $userItemId, 'type' => $v['type'],
                'title' => $v['title'], 'icon' => $v['icon'], 'link' => $v['link'],
                'pid' => $v['pid'], 'is_show' => $v['is_show'],
                'addtime' => toDate(), 'uptime' => toDate(),
            ]);
            //复制数据
            $xmDataTotal = $this->dbConn($this->dbXmData)->where('menu_id', $v['id'])->count();
            if (!$xmDataTotal) {
                $tmpDataOnes = $this->dbConn($this->dbTmpData)->where('menu_id', $v['id'])->get();
                foreach ($tmpDataOnes as $vv) {
                    $vv = (array) $vv;
                    $this->dbConn($this->dbXmData)->insertGetId([
                        'uid' => $uid, 'tmp_id' => $itemId, 'tmp_data_id' => $vv['id'],
                        'user_item_id' => $userItemId, 'type' => $vv['type'], 'menu_id' => $vv['menu_id'],
                        'field_cn' => $vv['field_cn'], 'field_en' => $vv['field_en'],
                        'field_type' => $vv['field_type'], 'field_val' => $vv['field_val'],
                        'disabled' => $vv['disabled'], 'tmp_menu_id' => $vv['id'],
                        'addtime' => toDate(), 'uptime' => toDate(),
                    ]);
                }
            }
            //查看下级
            $this->copyMenu($uid, $itemId, $userItemId, $v['id']);
        }
        return true;
    }

    //用户打包
    public function rarAdd($uid, $itemId, $fpath)
    {
        return $this->dbConn($this->dbXmRar)->insertGetId([
            'uid' => $uid, 'user_item_id' => $itemId, 'fpath' => $fpath, 'addtime' => toDate(),
        ]);
    }

    //用户下载
    public function rarDown($id)
    {
        return $this->dbConn($this->dbXmRar)->where('id', $id)->increment('down_num', 1);
    }

    /**
     * 文档列表
     * @param int $item_id 项目ID
     * @param int $client_type 用户端类型：1前台，2后台
     */
    public function getDocIndex($item_id, $client_type = 0)
    {
        $db = $this->dbConn($this->dbXmDoc)
            ->where('del', 0)
            ->where('user_item_id', $item_id);
        if ($client_type) {
            $db = $db->where('client_type', $client_type);
        }
        $res = $db->orderBy('id', 'asc')->get();
        if (!count($res)) {
            return $this->toback(0, '没有项目', []);
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
            ];
        }
        return $this->toback(0, '', $arys);
    }

    //文档详情
    public function getDocOne($docId)
    {
        $res = (array) $this->dbConn($this->dbXmDoc)->where('id', $docId)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有接口');
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'url' => env('DOMAIN') . $res['url'],
            'req_json' => $res['req_json'],
        ];
        return $this->toback(0, '', $arys);
    }
}